﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTime>
#pragma execution_character_set("utf-8")

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("客户端端口");
    udpSocket = new QUdpSocket(this);
//    udpSocket->bind(9999);
    connect(udpSocket,&QUdpSocket::readyRead,this,&MainWindow::dealMsg);

}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::dealMsg()
{
    //读取对方发送的内容
     char buf[1024] = {0};           //内容
     QHostAddress cliAddr;           //对方地址
     quint16 port;                   //对方端口
     qint64 len = udpSocket->readDatagram(buf,sizeof(buf),&cliAddr,&port);
     //添加时间
     QTime cur_time = QTime::currentTime();
     QString time_info = cur_time.toString("hh:mm:ss");
     if(len >0)
     {
         //获取到文本格式化 如 [192.168.1.1 : 8888]aaaa 的格式
         QString str = QString("[%1:%2] %3 [%4]")
                 .arg(cliAddr.toString())
                 .arg(port)
                 .arg(buf)
                 .arg(time_info);
         ui->textEdit->append(str);
     }
}


void MainWindow::on_pB_send_clicked()
{
    QString ip = ui->lE_IP->text();
    qint16 port = ui->lE_port->text().toInt();

    QString str = ui->textEdit->toPlainText();

    udpSocket->writeDatagram(str.toUtf8(),QHostAddress(ip),port);

    ui->textEdit->clear();
}

void MainWindow::on_pB_close_clicked()
{
    udpSocket->disconnectFromHost();
    udpSocket->close();
    qDebug() << "主服务器连接断开！";
    this->close();
}
